import { LockOutlined, UploadOutlined, UserOutlined } from '@ant-design/icons';
import { useMutation } from '@tanstack/react-query';
import type { UploadProps } from 'antd';
import { Button, Card, Form, Input, message, Radio, Select, Upload } from 'antd';
import type { RcFile } from 'antd/es/upload';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import api from '@/apis/api';
import { Messages } from '@/components/Messages/Messages';
import { Logger } from '@/components/useLogger';
import { systemType } from '@/constant/systemType';
import DeviceConfigureModal from '@/pages/devManage/components/DeviceInfoModal';
import { getHeaders } from '@/utils/ReqInstance/axios';
import { UsbRegisterRole } from '@/utils/usbKey/register';

import styles from './styles.module.less';

const { Option } = Select;

const Init1 = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [keyImportMode, setKeyImportMode] = useState(0);
  const [file, setFile] = useState<RcFile | null>(null);
  const [fileList, setFileList] = useState<RcFile[]>([]);
  const [visible, setVisible] = useState(false);

  const getFileExtension = (filename: string) => {
    if (!filename) return ''; // 文件名为空的情况
    const parts = filename.split('.');
    if (!parts || parts.length === 0 || (parts[0] === '' && parts.length === 1)) {
      return ''; // 没有扩展名或隐藏文件
    }
    return parts.pop()?.toLowerCase() || ''; // 获取扩展名并转换为小写
  };

  const props: UploadProps = {
    name: 'file',
    maxCount: 1,
    accept: '.hust',
    headers: {
      ...getHeaders(),
      'accept-encoding': 'zh-CN,zh;q=0.9',
      'accept-language': 'gzip, deflate, brz',
    },
    beforeUpload: (file: RcFile) => {
      const allowedExtensions = ['hust'];
      const fileExtension = getFileExtension(file.name);
      const isAllowedExtension = allowedExtensions.includes(fileExtension);

      if (!isAllowedExtension) {
        Messages.error('请上传hust文件');
        return false;
      }
      const size = file.size;
      if (size === 0) {
        Messages.error('文件大小不能为0');
        return false;
      }

      if (size > 10 * 1024 * 1024) {
        Messages.error('上传文件限制在10MB以内');
        return false;
      }
      setFile(file); // Save the file to the state
      setFileList([file]); // Update the file list
      return false; // Prevent auto upload
    },
    onRemove: () => {
      setFile(null);
      setFileList([]);
    },
  };

  const Register = useMutation({
    mutationFn: async (params: any) => {
      return api.InitDevice(params); // Use FormData for the request
    },
    onSuccess: (res: any) => {
      if (res?.success) {
        // localStorage.setItem('isFirstVisit', 'false');
        message.open({
          type: 'success',
          key: 'register',
          content: '初始化成功，跳转至登录页',
          duration: 1,
        });
        navigate('/login');
      } else {
        message.open({
          type: 'error',
          key: 'register',
          content: `初始化失败，${res?.message}`,
          duration: 1,
        });
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.open({
        type: 'error',
        key: 'register',
        content: '初始化失败',
        duration: 1,
      });
    },
  });

  const handleRegisterUser = async (values: any) => {
    try {
      await form.validateFields();
      message.open({
        type: 'info',
        key: 'register',
        content: '初始化中...请稍侯',
      });
      const publickey = await UsbRegisterRole();
      Logger('public_key', publickey);
      Register.mutate({
        file: file,
        grant: 0,
        username: values.name,
        password: values.password,
        public_key: publickey,
        log_class: values.log_level,
        generation: keyImportMode,
        key_password: values.keyPassword,
      });
    } catch (error: any) {
      Logger(error.message);
    }
  };

  const handleModeChange = (e: any) => {
    setKeyImportMode(e.target.value);
    setFile(null);
    setFileList([]);
  };

  useEffect(() => {
    const fetchInitializationStatus = async () => {
      try {
        // 假设你有一个 API 可以获取初始化状态
        const response: any = await api.GetInitedStatus();
        const data = response?.data;
        const isInited = data?.status === 0;
        if (isInited) {
          console.log('已初始化');
          // navigate('/login');
        }
      } catch (error) {
        Logger(error);
      }
    };

    fetchInitializationStatus();
  }, [navigate]);

  return (
    <>
      <div className={styles.initPage}>
        <div className={styles.initBox}>
          <h3 className={styles.title}>
            {systemType === 'school'
              ? '哈尔滨理工大学 国密服务器密码机'
              : '中数国密商用服务器密码机'}
          </h3>
          <h3 className={styles.title}>设备初始化</h3>
          <Card>
            <div
              style={{
                textAlign: 'left',
                marginBottom: '16px',
                fontSize: '14px',
                color: 'red',
              }}
            >
              提示：初始化前请插入usbkey！
            </div>
            <Form form={form} onFinish={handleRegisterUser}>
              <Form.Item
                name="mode"
                label="密钥生成"
                rules={[{ required: true, message: '请选择密钥生成方式!' }]}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
                initialValue={0}
              >
                <Radio.Group onChange={handleModeChange} value={keyImportMode}>
                  <Radio value={0}>自动生成</Radio>
                  <Radio value={1}>导入</Radio>
                </Radio.Group>
                <Upload {...props} fileList={fileList}>
                  <Button
                    style={{ display: keyImportMode === 0 ? 'none' : '' }}
                    icon={<UploadOutlined />}
                  >
                    导入
                  </Button>
                </Upload>
              </Form.Item>
              <Form.Item
                name="keyPassword"
                label="密钥口令"
                rules={[{ required: keyImportMode !== 0, message: '请输入密钥口令!' }]}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
                style={{ display: keyImportMode === 0 ? 'none' : '' }}
              >
                <Input.Password type="password" placeholder="请输入密钥口令" />
              </Form.Item>
              <Form.Item
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
                name="log_level"
                label="日志等级"
                rules={[{ required: true, message: '请选择日志等级!' }]}
              >
                <Select placeholder="请选择日志等级" allowClear>
                  <Option value={0}>完全记录</Option>
                  <Option value={1}>错误记录</Option>
                </Select>
              </Form.Item>
              <Form.Item
                name="name"
                label="管理员账号"
                rules={[{ required: true, message: '请输入管理员账号!' }]}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="请输入管理员账号"
                  maxLength={30}
                />
              </Form.Item>
              <Form.Item
                name="password"
                label="管理员密码"
                rules={[{ required: true, message: '请输入管理员密码!' }]}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  type="password"
                  placeholder="请输入管理员密码"
                  minLength={4}
                />
              </Form.Item>
              <Form.Item
                label="确认密码"
                name="rpassword"
                rules={[
                  ({ getFieldValue }) => ({
                    validator(rule, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve(rule);
                      }
                      return Promise.reject('两次密码不同！');
                    },
                  }),
                  { required: true, message: '请再输入管理员密码!' },
                ]}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
              >
                <Input.Password
                  autoComplete="new-password"
                  placeholder="请再输入管理员密码"
                  prefix={<LockOutlined />}
                />
              </Form.Item>
              <a
                onClick={() => setVisible(true)}
                style={{
                  display: 'block',
                  textAlign: 'left',
                  color: '#1890ff',
                  marginBottom: '16px',
                  marginLeft: '8px',
                }}
              >
                查看设备基本信息
              </a>
              <Form.Item>
                <Button type="primary" htmlType="submit" className={styles.submitButton}>
                  初始化
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </div>
      </div>

      <DeviceConfigureModal visible={visible} setVisible={setVisible} />
    </>
  );
};

export default Init1;
